<template>
  <div class="main">
    <div :class="['container', isLogin ? 'b-container' : 'a-container']">
      <component :is="isLogin ? 'Login' : 'Register'" @submit="handleSubmit"></component>
    </div>
    <!-- 动态切换组件 -->
    <div class="switch" id="switch-cnt">
      <div class="switch__circle"></div>
      <div class="switch__circle switch__circle--t"></div>
      <div :class="['switch__container', isLogin ? 'is-hidden' : '']" id="switch-c1">
        <h2 class="switch__title title">欢迎回来!</h2>
        <p class="switch__description description">为了与我们保持联系，请使用您的个人信息登录</p>
        <button @click="toggleView" class="switch__button button switch-btn">SIGN IN</button>
      </div>
      <div :class="['switch__container', isLogin ? '' : 'is-hidden']" id="switch-c2">
        <h2 class="switch__title title">你好 朋友!</h2>
        <p class="switch__description description">输入您的个人信息，与我们一起开始旅程</p>
        <button @click="toggleView" class="switch__button button switch-btn">SIGN UP</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
// 外部引入
import { defineComponent, ref } from 'vue';
import Register from '@/components/User/Register.vue';
import Login from '@/components/User/Login.vue';
import { register, login, User } from "@/service/user/userService";
import { ElMessage } from "element-plus";
import router from "@/router"
export default defineComponent({
  // 组件注册
  components: {
    Register,
    Login,
  },
  setup() {
    // 属性初始化
    const isLogin = ref(true);
    const loading = ref(false);
    const errorMessage = ref('');
    const toggleView = () => {
      isLogin.value = !isLogin.value;
      errorMessage.value = '';
    };
    // 事件响应
    const handleSubmit = async (data: User) => {
      loading.value = true;
      try {
        // 登陆注册请求处理
        if (isLogin.value) {
          login(data).then(()=>{
            ElMessage?.success("登陆成功");
            router.push("/dashboard")
          })
          
        } else {
          register(data).then(()=>{
            ElMessage?.success("注册成功");

            toggleView();

          })
        }
      } catch (error: any) {
        errorMessage.value = error.message;
        ElMessage?.error(errorMessage.value);
      } finally {
        loading.value = false;
      }
    };

    return {
      isLogin,
      toggleView,
      handleSubmit,
      loading,
      errorMessage,
    };
  },
});
</script>

<style lang="less" scoped>
@import '@/assets/css/user.less';
</style>